package de.tu_cottbus.portal.security.ldap;

import java.util.Properties;

import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.model.User;
import com.liferay.portal.model.UserGroup;
import com.liferay.portal.security.ldap.DefaultLDAPToPortalConverter;
import com.liferay.portal.security.ldap.LDAPUser;
import com.liferay.portal.service.UserGroupLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;

/**
 * @author Andreas Fehn (fehnandr@tu-cottbus.de)
 */
public class CustomLDAPToPortalConverter extends DefaultLDAPToPortalConverter {

	@Override
	public LDAPUser importLDAPUser(long companyId, Attributes attributes,
			Properties userMappings, Properties userExpandoMappings,
			Properties contactMappings, Properties contactExpandoMappings,
			String password) throws Exception {

		LDAPUser ldapUser = super.importLDAPUser(companyId, attributes,
				userMappings, userExpandoMappings, contactMappings,
				contactExpandoMappings, password);

		Attribute eT = attributes.get("employeeType");

		if (eT == null) {
			return ldapUser;
		}

		String type = eT.get().toString();
		UserGroup group;

		try {
			group = UserGroupLocalServiceUtil.getUserGroup(companyId, type);
		} catch (PortalException e) {
			// Die UserGroup existiert noch nicht und muss erstellt werden.
			// Der Besitzer der Gruppe soll der Admin-Account 'test' sein.
			User owner = UserLocalServiceUtil.getUserByScreenName(companyId,
					"test");
			group = UserGroupLocalServiceUtil.addUserGroup(owner.getUserId(),
					companyId, type, "");
			UserGroupLocalServiceUtil.addUserGroup(group);
		}

		ldapUser.setUserGroupIds(new long[] { group.getUserGroupId() });

		return ldapUser;
	}
}
